package indi.luckly.config.shiro;


import indi.luckly.config.cache.RedisCacheManager;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean("filterShiroFilterRegistrationBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier(value = "webSecurityManager") DefaultWebSecurityManager manager) {
        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("token", new TokenFilter());
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(manager);
        HashMap<String, String> hashMap = new HashMap<>();

        shiroFilterFactoryBean.setFilterChainDefinitionMap(hashMap);
        shiroFilterFactoryBean.setFilters(filterMap);
        return shiroFilterFactoryBean;
    }

    @Bean(value = "webSecurityManager")
    public DefaultWebSecurityManager getWebSecurityManager(@Qualifier("customRealm") Realm realm) {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
//        //配置缓存
//        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
//        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
//        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
//        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
//        manager.setSubjectDAO(subjectDAO);
        // manager.setSessionManager(new ShiroSessionManager());
        manager.setRealm(realm);
        return manager;
    }

    @Bean(value = "customRealm")
    public CustomRealm getCustomRealm() {
        CustomRealm customRealm = new CustomRealm();
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        hashedCredentialsMatcher.setHashIterations(1024);
        customRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        //配置redis缓存
        customRealm.setCacheManager(new RedisCacheManager());
        customRealm.setCachingEnabled(true);
        customRealm.setAuthenticationCachingEnabled(true);
        customRealm.setAuthorizationCachingEnabled(true);
        customRealm.setAuthenticationCacheName("AuthenticationCache");
        customRealm.setAuthorizationCacheName("AuthorizationCache");
        return customRealm;
    }


}
